/*
 * 文件名： CheckOrderPabScanPayImpl.java
 * 
 * 工程名称: checkorder-service
 *
 * Gopay
 *
 * 创建日期： 2017年8月16日
 *
 * Copyright(C) 2017, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.checkorder.service.impl.scan;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankOrderStatus;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.PabConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.ScanPayBaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.pab.agpay.PabTransResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayRefundQueryResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayStatusResMsg;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.ScanPayInteractRemoteService;

/**
 * 扫码支付平安银行渠道结果查询
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2017年8月16日
 */
public class CheckOrderPabScanPayImpl implements BankOrderService {

	private final static Logger logger = LoggerFactory.getLogger("SCAN-PAB");

	@Resource(name = "wechatScanClient")
	private ScanPayInteractRemoteService scanClient;

	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		/**
		 * 对单返回对象
		 */
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());

		ScanPayBaseMessage message = new ScanPayBaseMessage();
		// 国付宝系统订单号
		message.setOrderId(bankOrder.getOrderId()); 
		// 上送银行单号
		message.setBankOrderId(bankOrder.getOutOrderId());
		// 银行通道码
		message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
		// 银行业务产品码
		message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
		message.setBank(bankOrder.getBankCode());

		Result result = new Result();
		try {
			if (BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode())) {
				/**
				 * 退款交易请求退款查询接口
				 */
				message.setTkOriBankOrderId(bankOrder.getOriOutOrderId());
				result = scanClient.refundQuery(message);
				return refundCheckOrder(result, bankOrder);
			} else {
				result = scanClient.orderQuery(message);
			}
			if (result == null || !result.isSuccess()) {
				logger.error("scanClient fail.");
				if (result == null || ProcCodeConstants.PROC_CODE_100F1002.equals(result.getResultCode())
						|| ProcCodeConstants.PROC_CODE_100E7027.equals(result.getResultCode())
						|| ProcCodeConstants.PROC_CODE_100E6063.equals(result.getResultCode())) {
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
				}
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}

			@SuppressWarnings("unchecked")
			PabTransResMsg<PayStatusResMsg> res = (PabTransResMsg<PayStatusResMsg>) result.getDefaultModel();
			if (res == null) {
				/**
				 * 查询结果为空
				 */
				logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:"
						+ ProcCodeConstants.PROC_CODE_100E6022 + " err:bis query is null.");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("返回对账结果为空");
				return checkOrderResult;
			}
			PayStatusResMsg queryResult = res.getBody();

			if (StringUtils.equals("0", res.getErrcode())) {
				/**
				 * 订单状态（1交易成功，2待支付，4已取消，9等待用户输入密码确认）
				 */
				if (StringUtils.equals(PabConstants.ORDER_SUCCESS, queryResult.getStatus())) {

					checkOrderResult.setSuccess(true);

					InAccInfo accInfo = new InAccInfo();
					accInfo.setOrderId(bankOrder.getOrderId());
					accInfo.setAmount(res.getAmount());
					accInfo.setRetCode("00");
					accInfo.setCardType(BankCardType.Unknown.toString());
					checkOrderResult.setAccInfo(accInfo);
					logger.error("平安银行扫码支付订单：" + bankOrder.getOrderId() + "，交易成功。");
				} else if (StringUtils.equals(PabConstants.ORDER_CANCEL, queryResult.getStatus())) {
					checkOrderResult.setBankFailure(true);
					checkOrderResult.setErrMsg("扫码交易订单已经取消！");
					logger.error("扫码支付订单：" + bankOrder.getOrderId() + "，交易失败" + "返回码：" + queryResult.getStatus()
							+ "。返回信息为：" + res.getMsg());
				} else if (StringUtils.equals(PabConstants.ORDER_WAIT, queryResult.getStatus())
						|| StringUtils.equals(PabConstants.ORDER_WAIT_PWD, queryResult.getStatus())) {
					checkOrderResult.setErrMsg("扫码订单进行中！");
					logger.error("扫码支付订单：" + bankOrder.getOrderId() + "，交易处理中" + "返回码：" + queryResult.getStatus()
							+ "。返回信息为：" + res.getMsg());
				} else {
					checkOrderResult.setErrMsg("扫码返回交易状态不明");
					logger.error("扫码支付订单：" + bankOrder.getOrderId() + "，返回交易状态不明，系统暂不处理" + "返回码："
							+ queryResult.getStatus() + "。返回信息为：" + res.getMsg());
				}
			} else {
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				logger.error("支付订单：" + bankOrder.getOrderId() + "，查询失败" + "err_code：" + res.getErrcode() + "。错误信息为："
						+ res.getMsg());
			}
			return checkOrderResult;
		} catch (Exception e) {
			logger.error("scanClient fail.", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("平安扫码对账异常");
			return checkOrderResult;
		}
	}

	/**
	 * 
	 * 功能描述：退款订单查询处理
	 *
	 * @param result
	 * @param bankOrder
	 * @return
	 * 
	 * @author 宣广海
	 *
	 * @since 2017年8月16日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public CheckOrderResult refundCheckOrder(Result result, BankOrder bankOrder) {

		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		if (result == null || !result.isSuccess()) {
			logger.error("refund bankClient fail.");
			if (result == null || ProcCodeConstants.PROC_CODE_100F1002.equals(result.getResultCode())
					|| ProcCodeConstants.PROC_CODE_100E7027.equals(result.getResultCode())
					|| ProcCodeConstants.PROC_CODE_100E6063.equals(result.getResultCode())) {
				BankCountDownLatch.failIncrease(bankOrder.getBankCode());
				checkOrderResult.setCommunicateError(true);
			}
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6062);
			checkOrderResult.setErrMsg("系统返回对账结果为空");
			return checkOrderResult;
		}
		PabTransResMsg<PayRefundQueryResMsg> res = (PabTransResMsg<PayRefundQueryResMsg>) result.getDefaultModel();
		if (res == null) {
			/**
			 * 支付宝:只有一种状态【1.退款成功】，接口返回了查询数据，则代表退款成功，如果没有查询到则代表未退款成功
			 */
			if("ALIPAY".equals(bankOrder.getBankCode())){
				checkOrderResult.setErrMsg("银行返回退款交易处理中.");
				return checkOrderResult;
			}
			// 查询订单为空
			logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E5062
					+ " err:bis query is null.");
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("银行返回对账结果为空");
			return checkOrderResult;
		}

		if (StringUtils.equals("0", res.getErrcode())) {
			PayRefundQueryResMsg queryResult = res.getBody();
			//状态（1.退款成功2.退款处理中 3.退款异常4.退款关闭）
			if (StringUtils.equals(PabConstants.REFUND_ORDER_SUCCESS, queryResult.getStatus())) {
				// 成功处理
				checkOrderResult.setSuccess(true);
				InAccInfo accInfo = new InAccInfo();
				accInfo.setOrderId(bankOrder.getOrderId());
				//平安银行退款查询不返回退款金额
				accInfo.setAmount(bankOrder.getSendBankAmt());
				accInfo.setRetCode("00");
				accInfo.setCardType(BankCardType.Unknown.toString());
				checkOrderResult.setAccInfo(accInfo);
				logger.error("平安扫码支付refund订单：" + bankOrder.getOrderId() + "的交易银行处理成功。");
			} else if (StringUtils.equals(PabConstants.REFUND_ORDER_WAIT, queryResult.getStatus())) {
				logger.error("平安扫码支付refund订单：" + bankOrder.getOrderId() + "的退款交易进行中。");
				String errMsg = res.getMsg();
				if (errMsg != null) {
					checkOrderResult.setErrMsg(errMsg);
				} else {
					checkOrderResult.setErrMsg("银行返回退款交易处理中.");
				}
			}else if (StringUtils.equals(PabConstants.REFUND_ORDER_EXCEPTION, queryResult.getStatus())) {
				checkOrderResult.setBankFailure(true);
				InAccInfo accInfo = new InAccInfo();
				accInfo.setOrderId(bankOrder.getOrderId());
				//平安银行退款查询不返回退款金额
				accInfo.setAmount(bankOrder.getSendBankAmt());
				accInfo.setRetCode("01");
				accInfo.setCardType(BankCardType.Unknown.toString());
				checkOrderResult.setAccInfo(accInfo);
				logger.error("平安银行扫码支付refund订单：" + bankOrder.getOrderId() + "的交易退款失败。" + "返回码：" + res.getErrcode()
						+ "，返回信息为：" + res.getMsg());
				String errMsg = res.getMsg();
				if (errMsg != null) {
					checkOrderResult.setErrMsg(errMsg);
				} else {
					checkOrderResult.setErrMsg("银行返回退款交易失败。");
				}}
		} else if (StringUtils.equals("8023", res.getErrcode())) {
			// 失败处理
			checkOrderResult.setBankFailure(true);
			InAccInfo accInfo = new InAccInfo();
			accInfo.setOrderId(bankOrder.getOrderId());
			//平安银行退款查询不返回退款金额
			accInfo.setAmount(bankOrder.getSendBankAmt());
			accInfo.setRetCode("01");
			accInfo.setCardType(BankCardType.Unknown.toString());
			checkOrderResult.setAccInfo(accInfo);
			logger.error("平安银行扫码支付refund订单：" + bankOrder.getOrderId() + "的交易退款失败。" + "返回码：" + res.getErrcode()
					+ "，返回信息为：" + res.getMsg());
			String errMsg = res.getMsg();
			if (errMsg != null) {
				checkOrderResult.setErrMsg(errMsg);
			} else {
				checkOrderResult.setErrMsg("银行返回退款交易失败。");
			}
		} else if (StringUtils.equals("8002", res.getErrcode()) || StringUtils.equals("8018", res.getErrcode())) {
			logger.error("平安银行扫码支付refund订单：" + bankOrder.getOrderId() + "的退款交易不存在" + "返回码：" + res.getErrcode()
					+ "，返回信息为：" + res.getMsg());
			String errMsg = res.getMsg();
			if (errMsg != null) {
				checkOrderResult.setErrMsg(errMsg);
			} else {
				checkOrderResult.setErrMsg("银行返回退款交易不存在。");
			}
			// 查询订单不存在
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
		} else {
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("系统返回对账结果为空");
			if (bankOrder.getOrderStatus().equals(BankOrderStatus.ACCEPTED)) {
				checkOrderResult.setErrMsg("系统返回对账结果为空,订单已受理，请耐心等待");
			}
			logger.error("支付退款订单：" + bankOrder.getOrderId() + "，查询失败" + "err_code：" + res.getErrcode()
					+ "。返回信息为：" + res.getMsg());
		}
		return checkOrderResult;
	}

	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bankBus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bankBus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
